#!/bin/bash

###########################################################
#                勾股系统自动化安装脚本 (Ubuntu版)          #
# 功能:                                                  #
# 1. 检测并处理已安装的Nginx、MySQL、PHP服务               #
# 2. 可选择安装勾股OA、勾股博客、勾股开发系统               #
# 3. 每个系统可自定义HTTP/HTTPS端口(带默认值)              #
# 4. 自动安装缺失的Nginx、PHP 8.3、MySQL 8.0              #
# 5. 根据是否提供域名自动配置HTTP/HTTPS访问方式            #
# 6. 检测到相同数据库时先删除再重新创建                     #
# 7. 使用稳定的Nginx配置格式                              #
# 8. 完整的目录权限设置                                   #
# 版本: 5.0-ubuntu                                       #
###########################################################

# 检查是否为 root 用户
if [ "$(id -u)" -ne 0 ]; then
    echo "请使用 sudo 或以 root 用户运行此脚本！" >&2
    exit 1
fi

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 获取本机IP地址
get_local_ip() {
    ip -o -4 addr show | awk '{print $4}' | cut -d'/' -f1 | grep -v '127.0.0.1' | head -n1
}

# 检查系统是否为Ubuntu
check_ubuntu() {
    if [ ! -f /etc/os-release ]; then
        echo -e "${RED}无法检测操作系统类型!${NC}"
        exit 1
    fi
    
    . /etc/os-release
    if [ "$ID" != "ubuntu" ]; then
        echo -e "${RED}此脚本仅支持 Ubuntu 系统!${NC}"
        echo -e "${YELLOW}检测到的系统: $ID${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}检测到 Ubuntu $VERSION_ID 系统，继续安装...${NC}"
}

# 显示欢迎信息
echo -e "${GREEN}=== 勾股系统安装脚本 (Ubuntu版) ===${NC}"

# 检查系统
check_ubuntu

###########################################################
#                 第一部分：服务状态检测                   #
###########################################################

echo -e "${BLUE}=== 检测系统服务状态 ===${NC}"

# 检测Nginx
NGINX_INSTALLED=false
NGINX_RUNNING=false
if command -v nginx &> /dev/null; then
    NGINX_INSTALLED=true
    if systemctl is-active --quiet nginx; then
        NGINX_RUNNING=true
        echo -e "${GREEN}✓ Nginx 已安装并运行中${NC}"
        nginx -v
    else
        echo -e "${YELLOW}⚠ Nginx 已安装但未运行${NC}"
    fi
else
    echo -e "${YELLOW}⚠ Nginx 未安装${NC}"
fi

# 检测MySQL
MYSQL_INSTALLED=false
MYSQL_RUNNING=false
if command -v mysql &> /dev/null; then
    MYSQL_INSTALLED=true
    if systemctl is-active --quiet mysql; then
        MYSQL_RUNNING=true
        echo -e "${GREEN}✓ MySQL 已安装并运行中${NC}"
        mysql --version
    else
        echo -e "${YELLOW}⚠ MySQL 已安装但未运行${NC}"
    fi
else
    echo -e "${YELLOW}⚠ MySQL 未安装${NC}"
fi

# 检测PHP
PHP_INSTALLED=false
PHP_FPM_RUNNING=false
PHP_VERSION_CURRENT=""
if command -v php &> /dev/null; then
    PHP_INSTALLED=true
    PHP_VERSION_CURRENT=$(php -v | grep -oP '^PHP \K[0-9]+\.[0-9]+' | head -1)
    echo -e "${GREEN}✓ PHP 已安装 (版本: $PHP_VERSION_CURRENT)${NC}"
    
    # 检测PHP-FPM
    if systemctl is-active --quiet php8.3-fpm || systemctl is-active --quiet php8.2-fpm || systemctl is-active --quiet php8.1-fpm || systemctl is-active --quiet php8.0-fpm || systemctl is-active --quiet php7.4-fpm; then
        PHP_FPM_RUNNING=true
        echo -e "${GREEN}✓ PHP-FPM 正在运行${NC}"
    else
        echo -e "${YELLOW}⚠ PHP-FPM 未运行${NC}"
    fi
else
    echo -e "${YELLOW}⚠ PHP 未安装${NC}"
fi

echo -e "${BLUE}=== 服务检测完成 ===${NC}"

###########################################################
#                 第二部分：用户输入配置                   #
###########################################################

# 1. 选择要安装的系统
echo -e "${YELLOW}=== 请选择要安装的系统 (可多选) ===${NC}"
echo "1. 勾股OA系统"
echo "2. 勾股博客系统"
echo "3. 勾股开发系统"
read -p "请输入选择 (多个选择用空格分隔，默认全选): " SYSTEMS_CHOICE

[ -z "$SYSTEMS_CHOICE" ] && SYSTEMS_CHOICE="1 2 3"
IFS=' ' read -ra SYSTEMS <<< "$SYSTEMS_CHOICE"

INSTALL_OA=false
INSTALL_BLOG=false
INSTALL_DEV=false

for system in "${SYSTEMS[@]}"; do
    case $system in
        1) INSTALL_OA=true ;;
        2) INSTALL_BLOG=true ;;
        3) INSTALL_DEV=true ;;
    esac
done

# 2. 获取安装目录
echo -e "${YELLOW}=== 请输入安装目录 ===${NC}"
if $INSTALL_OA && ! $INSTALL_BLOG && ! $INSTALL_DEV; then
    read -p "勾股OA安装目录 (默认: /www/wwwroot/office): " OA_INSTALL_DIR
    OA_INSTALL_DIR=${OA_INSTALL_DIR:-/www/wwwroot/office}
elif ! $INSTALL_OA && $INSTALL_BLOG && ! $INSTALL_DEV; then
    read -p "勾股博客安装目录 (默认: /www/wwwroot/blog): " BLOG_INSTALL_DIR
    BLOG_INSTALL_DIR=${BLOG_INSTALL_DIR:-/www/wwwroot/blog}
elif ! $INSTALL_OA && ! $INSTALL_BLOG && $INSTALL_DEV; then
    read -p "勾股开发系统安装目录 (默认: /www/wwwroot/dev): " DEV_INSTALL_DIR
    DEV_INSTALL_DIR=${DEV_INSTALL_DIR:-/www/wwwroot/dev}
else
    read -p "基础安装目录 (默认: /www/wwwroot): " BASE_INSTALL_DIR
    BASE_INSTALL_DIR=${BASE_INSTALL_DIR:-/www/wwwroot}
    
    $INSTALL_OA && OA_INSTALL_DIR="${BASE_INSTALL_DIR}/office"
    $INSTALL_BLOG && BLOG_INSTALL_DIR="${BASE_INSTALL_DIR}/blog"
    $INSTALL_DEV && DEV_INSTALL_DIR="${BASE_INSTALL_DIR}/dev"
fi

# 3. 获取MySQL配置信息
echo -e "${YELLOW}=== 请输入MySQL配置信息 ===${NC}"

# 如果MySQL已安装，尝试获取现有root密码
if $MYSQL_INSTALLED; then
    echo -e "${YELLOW}检测到系统已安装MySQL，请输入现有的MySQL root密码${NC}"
    while true; do
        read -s -p "MySQL root密码: " MYSQL_PASSWORD
        echo
        [ -z "$MYSQL_PASSWORD" ] && { echo -e "${RED}密码不能为空!${NC}"; continue; }
        break
    done
else
    read -p "MySQL root用户 (默认: root): " MYSQL_USER
    MYSQL_USER=${MYSQL_USER:-root}

    while true; do
        read -s -p "MySQL root密码 (必须输入): " MYSQL_PASSWORD
        echo
        [ -z "$MYSQL_PASSWORD" ] && { echo -e "${RED}密码不能为空!${NC}"; continue; }
        
        read -s -p "再次输入MySQL root密码确认: " MYSQL_PASSWORD_CONFIRM
        echo
        
        [ "$MYSQL_PASSWORD" != "$MYSQL_PASSWORD_CONFIRM" ] && \
            echo -e "${RED}两次输入的密码不一致!${NC}" || break
    done
fi

read -p "MySQL主机地址 (默认: 127.0.0.1): " MYSQL_HOST
MYSQL_HOST=${MYSQL_HOST:-127.0.0.1}

read -p "MySQL端口 (默认: 3306): " MYSQL_PORT
MYSQL_PORT=${MYSQL_PORT:-3306}

# 为每个系统设置数据库名称
if $INSTALL_OA; then
    read -p "勾股OA数据库名称 (默认: gouguoa): " OA_MYSQL_DB
    OA_MYSQL_DB=${OA_MYSQL_DB:-gouguoa}
fi

if $INSTALL_BLOG; then
    read -p "勾股博客数据库名称 (默认: gougublog): " BLOG_MYSQL_DB
    BLOG_MYSQL_DB=${BLOG_MYSQL_DB:-gougublog}
fi

if $INSTALL_DEV; then
    read -p "勾股开发系统数据库名称 (默认: gougudev): " DEV_MYSQL_DB
    DEV_MYSQL_DB=${DEV_MYSQL_DB:-gougudev}
fi

# 4. 获取Nginx端口配置
echo -e "${YELLOW}=== 请输入Nginx端口配置 ===${NC}"

if $INSTALL_OA; then
    read -p "勾股OA HTTP端口 (默认: 6061): " OA_HTTP_PORT
    OA_HTTP_PORT=${OA_HTTP_PORT:-6061}
    
    read -p "勾股OA HTTPS端口 (默认: 6062): " OA_HTTPS_PORT
    OA_HTTPS_PORT=${OA_HTTPS_PORT:-6062}
fi

if $INSTALL_BLOG; then
    read -p "勾股博客 HTTP端口 (默认: 6071): " BLOG_HTTP_PORT
    BLOG_HTTP_PORT=${BLOG_HTTP_PORT:-6071}
    
    read -p "勾股博客 HTTPS端口 (默认: 6072): " BLOG_HTTPS_PORT
    BLOG_HTTPS_PORT=${BLOG_HTTPS_PORT:-6072}
fi

if $INSTALL_DEV; then
    read -p "勾股开发 HTTP端口 (默认: 6081): " DEV_HTTP_PORT
    DEV_HTTP_PORT=${DEV_HTTP_PORT:-6081}
    
    read -p "勾股开发 HTTPS端口 (默认: 6082): " DEV_HTTPS_PORT
    DEV_HTTPS_PORT=${DEV_HTTPS_PORT:-6082}
fi

# 5. 域名配置
read -p "域名 (留空则使用IP地址): " DOMAIN_NAME
SERVER_NAME=${DOMAIN_NAME:-$(get_local_ip)}

###########################################################
#              第三部分：系统检测与软件安装                 #
###########################################################

# 配置阿里云源
configure_aliyun_repo() {
    echo -e "${GREEN}=== 配置Ubuntu阿里云源 ===${NC}"
    # 备份原有源
    cp /etc/apt/sources.list /etc/apt/sources.list.backup.$(date +%Y%m%d%H%M%S)
    sed -i 's/archive.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
    sed -i 's/security.ubuntu.com/mirrors.aliyun.com/g' /etc/apt/sources.list
    apt update
}

# 安装基础软件
install_base_software() {
    echo -e "${GREEN}=== 安装基础软件 ===${NC}"
    configure_aliyun_repo
    apt update -y
    apt upgrade -y
    apt install -y software-properties-common curl wget git unzip
}

# 安装Nginx（如果需要）
install_nginx_if_needed() {
    if ! $NGINX_INSTALLED; then
        echo -e "${GREEN}=== 安装Nginx ===${NC}"
        apt install -y nginx
        systemctl enable nginx
        systemctl start nginx
        NGINX_INSTALLED=true
        NGINX_RUNNING=true
    else
        echo -e "${YELLOW}=== Nginx 已存在，跳过安装 ===${NC}"
        # 确保Nginx运行
        if ! $NGINX_RUNNING; then
            systemctl start nginx
            NGINX_RUNNING=true
        fi
    fi
}

# 安装PHP（如果需要）
install_php_if_needed() {
    if ! $PHP_INSTALLED || [ "$PHP_VERSION_CURRENT" != "8.3" ]; then
        echo -e "${GREEN}=== 安装PHP 8.3及相关扩展 ===${NC}"
        
        # 添加PHP PPA源
        LC_ALL=C.UTF-8 add-apt-repository -y ppa:ondrej/php
        apt update -y
        
        # 如果已有其他PHP版本，先安装PHP8.3但不立即切换
        apt install -y php8.3 php8.3-fpm php8.3-xml php8.3-cli \
                      php8.3-mysql php8.3-pdo php8.3-mbstring php8.3-curl \
                      php8.3-fileinfo php8.3-gd php8.3-zip php8.3-opcache
        
        # 启用PHP 8.3 FPM
        systemctl enable php8.3-fpm
        systemctl start php8.3-fpm
        
        PHP_INSTALLED=true
        PHP_VERSION_CURRENT="8.3"
        echo -e "${GREEN}✓ PHP 8.3 安装完成${NC}"
    else
        echo -e "${YELLOW}=== PHP $PHP_VERSION_CURRENT 已存在 ===${NC}"
        
        # 确保安装必要的PHP扩展
        echo -e "${GREEN}=== 检查并安装必要的PHP扩展 ===${NC}"
        apt install -y php8.3-mysql php8.3-pdo php8.3-mbstring php8.3-curl \
                      php8.3-fileinfo php8.3-gd php8.3-zip php8.3-opcache 2>/dev/null || \
        echo -e "${YELLOW}部分扩展安装失败，可能版本不匹配，继续安装...${NC}"
        
        # 确保PHP-FPM运行
        if ! $PHP_FPM_RUNNING; then
            systemctl start php8.3-fpm
            PHP_FPM_RUNNING=true
        fi
    fi
}

# 安装MySQL（如果需要）
install_mysql_if_needed() {
    if ! $MYSQL_INSTALLED; then
        echo -e "${GREEN}=== 安装MySQL 8.0 ===${NC}"
        apt install -y mysql-server
        systemctl enable mysql
        systemctl start mysql
        MYSQL_INSTALLED=true
        MYSQL_RUNNING=true
        
        # 初始化MySQL密码
        echo -e "${GREEN}=== 初始化MySQL root密码 ===${NC}"
        mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$MYSQL_PASSWORD'; FLUSH PRIVILEGES;"
    else
        echo -e "${YELLOW}=== MySQL 已存在，跳过安装 ===${NC}"
        # 确保MySQL运行
        if ! $MYSQL_RUNNING; then
            systemctl start mysql
            MYSQL_RUNNING=true
        fi
    fi
}

# 修改PHP上传大小
modify_php_upload_size() {
    echo -e "${GREEN}=== 修改PHP上传大小限制 ===${NC}"
    
    if [ -z "$PHP_VERSION_CURRENT" ]; then
        PHP_VERSION_CURRENT=$(php -v | grep -oP '^PHP \K[0-9]+\.[0-9]+' | head -1)
    fi

    if [ -z "$PHP_VERSION_CURRENT" ]; then
        echo "未检测到 PHP 安装！" >&2
        return 1
    fi

    echo "检测到 PHP 版本: $PHP_VERSION_CURRENT"

    PHP_INI_PATH="/etc/php/$PHP_VERSION_CURRENT/fpm/php.ini"
    if [ ! -f "$PHP_INI_PATH" ]; then
        echo "未找到 $PHP_INI_PATH，尝试查找其他php.ini文件..."
        PHP_INI_PATH=$(php --ini | grep 'Loaded Configuration File' | awk '{print $4}')
        if [ -z "$PHP_INI_PATH" ] || [ ! -f "$PHP_INI_PATH" ]; then
            echo "未找到 php.ini 文件，跳过上传大小修改" >&2
            return 1
        fi
    fi

    # 备份php.ini
    cp "$PHP_INI_PATH" "${PHP_INI_PATH}.backup.$(date +%Y%m%d%H%M%S)"

    # 修改 upload_max_filesize 和 post_max_size
    echo "正在修改 $PHP_INI_PATH ..."
    sed -i -E "s/^(upload_max_filesize\s*=\s*).*\$/\1100M/" "$PHP_INI_PATH"
    sed -i -E "s/^(post_max_size\s*=\s*).*\$/\1100M/" "$PHP_INI_PATH"

    # 重启 PHP-FPM
    PHP_FPM_SERVICE="php$PHP_VERSION_CURRENT-fpm"
    if systemctl is-active --quiet "$PHP_FPM_SERVICE"; then
        echo "正在重启 $PHP_FPM_SERVICE ..."
        systemctl restart "$PHP_FPM_SERVICE"
    else
        echo "启动 $PHP_FPM_SERVICE ..."
        systemctl start "$PHP_FPM_SERVICE"
    fi

    echo "PHP上传大小修改完成！"
}

# 执行安装
echo -e "${BLUE}=== 开始安装必要的软件 ===${NC}"
install_base_software
install_nginx_if_needed
install_php_if_needed
install_mysql_if_needed
modify_php_upload_size

###########################################################
#              第四部分：系统配置与部署                     #
###########################################################

# 配置MySQL
configure_mysql() {
    echo -e "${GREEN}=== 配置MySQL ===${NC}"
    
    # 创建临时MySQL配置文件
    mysql_config="$(mktemp)"
    echo "[client]" > "$mysql_config"
    echo "user=root" >> "$mysql_config"
    echo "password=$MYSQL_PASSWORD" >> "$mysql_config"
    echo "host=$MYSQL_HOST" >> "$mysql_config"
    echo "port=$MYSQL_PORT" >> "$mysql_config"

    # 测试MySQL连接
    if ! mysql --defaults-extra-file="$mysql_config" -e "SELECT 1" &>/dev/null; then
        echo -e "${YELLOW}=== MySQL连接失败，尝试修复 ===${NC}"
        
        # 尝试多种方式连接MySQL
        if mysql -u root -p"$MYSQL_PASSWORD" -e "SELECT 1" &>/dev/null; then
            echo -e "${GREEN}√ MySQL连接成功${NC}"
        else
            echo -e "${YELLOW}→ 尝试安全模式修复...${NC}"
            sudo systemctl stop mysql
            sudo mkdir -p /var/run/mysqld
            sudo chown mysql:mysql /var/run/mysqld
            sudo mysqld_safe --skip-grant-tables --skip-networking &
            sleep 5
            
            mysql -u root <<MYSQL_SCRIPT
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$MYSQL_PASSWORD';
FLUSH PRIVILEGES;
EXIT;
MYSQL_SCRIPT
            
            sudo pkill mysqld
            sleep 2
            sudo systemctl start mysql
            sleep 3
        fi
    else
        echo -e "${GREEN}√ MySQL连接成功${NC}"
    fi

    # 创建数据库函数（检测并删除已存在数据库）
    create_database() {
        local db_name=$1
        local db_user=$2
        
        echo -e "${GREEN}=== 处理数据库 $db_name ===${NC}"
        
        # 检查数据库是否已存在
        if mysql --defaults-extra-file="$mysql_config" -e "USE $db_name" &>/dev/null; then
            echo -e "${YELLOW}⚠ 数据库 $db_name 已存在，正在删除...${NC}"
            if mysql --defaults-extra-file="$mysql_config" <<DELETE_DB_SCRIPT
DROP DATABASE IF EXISTS $db_name;
DROP USER IF EXISTS '$db_user'@'localhost';
FLUSH PRIVILEGES;
DELETE_DB_SCRIPT
            then
                echo -e "${GREEN}✓ 旧数据库 $db_name 删除成功${NC}"
            else
                echo -e "${RED}× 删除旧数据库 $db_name 失败!${NC}"
                return 1
            fi
        fi

        # 创建新数据库
        echo -e "${GREEN}正在创建新数据库 $db_name ...${NC}"
        if mysql --defaults-extra-file="$mysql_config" <<CREATE_DB_SCRIPT
CREATE DATABASE IF NOT EXISTS $db_name DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '$db_user'@'localhost' IDENTIFIED BY '$MYSQL_PASSWORD';
GRANT ALL PRIVILEGES ON $db_name.* TO '$db_user'@'localhost';
FLUSH PRIVILEGES;
CREATE_DB_SCRIPT
        then
            echo -e "${GREEN}✓ 数据库 $db_name 创建成功${NC}"
            
            # 验证数据库创建
            if mysql --defaults-extra-file="$mysql_config" -e "USE $db_name; SHOW TABLES;" &>/dev/null; then
                echo -e "${GREEN}✓ 数据库 $db_name 验证通过${NC}"
            else
                echo -e "${YELLOW}⚠ 数据库 $db_name 创建但验证失败${NC}"
            fi
        else
            echo -e "${RED}× 数据库 $db_name 创建失败!${NC}"
            echo -e "${YELLOW}请手动执行以下命令:${NC}"
            echo "1. 登录MySQL: mysql -u root -p"
            echo "2. 依次执行:"
            echo "   DROP DATABASE IF EXISTS $db_name;"
            echo "   DROP USER IF EXISTS '$db_user'@'localhost';"
            echo "   CREATE DATABASE IF NOT EXISTS $db_name DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
            echo "   CREATE USER IF NOT EXISTS '$db_user'@'localhost' IDENTIFIED BY '$MYSQL_PASSWORD';"
            echo "   GRANT ALL PRIVILEGES ON $db_name.* TO '$db_user'@'localhost';"
            echo "   FLUSH PRIVILEGES;"
            echo "3. 按回车键继续安装..."
            read -p "按回车键继续..."
            return 1
        fi
    }

    # 为每个系统创建数据库
    if $INSTALL_OA; then
        create_database "$OA_MYSQL_DB" "$OA_MYSQL_DB"
    fi

    if $INSTALL_BLOG; then
        create_database "$BLOG_MYSQL_DB" "$BLOG_MYSQL_DB"
    fi

    if $INSTALL_DEV; then
        create_database "$DEV_MYSQL_DB" "$DEV_MYSQL_DB"
    fi

    rm -f "$mysql_config"
}

# 安装勾股系统
install_gougu_systems() {
    echo -e "${GREEN}=== 下载并安装勾股系统 ===${NC}"

    # 安装Composer
    echo -e "${GREEN}=== 安装Composer ===${NC}"
    if ! command -v composer &> /dev/null; then
        curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer || {
            echo -e "${RED}Composer安装失败!${NC}"
            exit 1
        }
    else
        echo -e "${YELLOW}✓ Composer 已安装${NC}"
    fi

    # 安装函数
    install_system() {
        local system_name=$1
        local git_url=$2
        local install_dir=$3
        
        echo -e "${GREEN}=== 安装 $system_name ===${NC}"
        mkdir -p "$(dirname "$install_dir")"

        # 备份已存在的目录
        if [ -d "$install_dir" ]; then
            BACKUP_DIR="${install_dir}.bak.$(date +%Y%m%d%H%M%S)"
            echo -e "${YELLOW}检测到已存在的安装目录，正在备份到 $BACKUP_DIR...${NC}"
            mv "$install_dir" "$BACKUP_DIR" || { 
                echo -e "${YELLOW}备份失败，尝试强制删除旧目录...${NC}"
                rm -rf "$install_dir"
            }
        fi

        # 克隆代码
        echo -e "${GREEN}正在克隆 $system_name 代码...${NC}"
        git clone "$git_url" "$install_dir" || {
            echo -e "${RED}克隆 $system_name 仓库失败!${NC}"
            exit 1
        }

        # 安装PHP依赖
        echo -e "${GREEN}=== 安装 $system_name PHP依赖 ===${NC}"
        cd "$install_dir"
        composer install --ignore-platform-reqs --no-interaction || {
            echo -e "${YELLOW}Composer安装过程中出现错误，尝试继续...${NC}"
        }
        
        echo -e "${GREEN}✓ $system_name 安装完成${NC}"
    }

    # 安装各系统
    if $INSTALL_OA; then
        install_system "勾股OA" "https://gitee.com/gouguopen/office.git" "$OA_INSTALL_DIR"
    fi

    if $INSTALL_BLOG; then
        install_system "勾股博客" "https://gitee.com/gouguopen/blog.git" "$BLOG_INSTALL_DIR"
    fi

    if $INSTALL_DEV; then
        install_system "勾股开发系统" "https://gitee.com/gouguopen/dev.git" "$DEV_INSTALL_DIR"
    fi
}

# 设置勾股系统权限
set_gougu_permissions() {
    echo -e "${GREEN}=== 设置勾股系统目录权限 ===${NC}"
    
    set_system_permissions() {
        local system_name=$1
        local install_dir=$2
        
        echo -e "${YELLOW}设置 $system_name 权限...${NC}"
        
        # 检查目录是否存在
        if [ ! -d "$install_dir" ]; then
            echo -e "${RED}× 目录不存在: $install_dir${NC}"
            return 1
        fi
        
        # 设置基本权限
        echo -e "  设置基本目录权限..."
        find "$install_dir" -type d -exec chmod 755 {} \;
        find "$install_dir" -type f -exec chmod 644 {} \;
        
        # 设置关键目录为777权限
        for dir in app public config runtime; do
            if [ -d "$install_dir/$dir" ]; then
                chmod -R 777 "$install_dir/$dir"
                echo -e "  ${GREEN}✓ 设置 $dir 目录权限为777${NC}"
            else
                echo -e "  ${YELLOW}⚠ 目录不存在: $install_dir/$dir${NC}"
            fi
        done
        
        # 设置特定子目录权限
        for subdir in uploads install; do
            if [ -d "$install_dir/public/$subdir" ]; then
                chmod -R 777 "$install_dir/public/$subdir"
                echo -e "  ${GREEN}✓ 设置 public/$subdir 目录权限为777${NC}"
            fi
        done
        
        # 设置文件所有者
        chown -R www-data:www-data "$install_dir"
        echo -e "  ${GREEN}✓ 设置文件所有者为 www-data${NC}"
        
        echo -e "${GREEN}✓ $system_name 权限设置完成${NC}"
    }

    if $INSTALL_OA; then
        set_system_permissions "勾股OA" "$OA_INSTALL_DIR"
    fi

    if $INSTALL_BLOG; then
        set_system_permissions "勾股博客" "$BLOG_INSTALL_DIR"
    fi

    if $INSTALL_DEV; then
        set_system_permissions "勾股开发系统" "$DEV_INSTALL_DIR"
    fi
    
    echo -e "${GREEN}✓ 所有系统权限设置完成${NC}"
}

# 创建Nginx snippets文件
create_nginx_snippets() {
    echo -e "${GREEN}=== 创建Nginx snippets配置 ===${NC}"
    
    # 创建snippets目录
    mkdir -p /etc/nginx/snippets
    
    # 创建fastcgi-php.conf文件
    cat > /etc/nginx/snippets/fastcgi-php.conf << 'EOF'
# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;

# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;

# Bypass the fact that try_files resets $fastcgi_path_info
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;

fastcgi_index index.php;
include fastcgi.conf;
EOF

    echo -e "${GREEN}✓ Nginx snippets配置创建完成${NC}"
}

# 配置Nginx
configure_nginx() {
    echo -e "${GREEN}=== 配置Nginx ===${NC}"

    # 创建snippets文件
    create_nginx_snippets

    # Ubuntu使用sites-available目录
    NGINX_CONF_DIR="/etc/nginx/sites-available"

    # 生成SSL证书
    echo -e "${GREEN}=== 生成SSL证书 ===${NC}"
    mkdir -p /data/ssl
    if [ -n "$DOMAIN_NAME" ]; then
        CN="$DOMAIN_NAME"
    else
        CN="$SERVER_NAME"
    fi

    if [ ! -f /data/ssl/cert.crt ] || [ ! -f /data/ssl/cert.key ]; then
        openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
            -keyout /data/ssl/cert.key \
            -out /data/ssl/cert.crt \
            -subj "/C=CN/ST=Beijing/L=Beijing/O=YourCompany/OU=IT/CN=$CN"
        echo -e "${GREEN}✓ SSL证书生成完成${NC}"
    else
        echo -e "${YELLOW}✓ SSL证书已存在，跳过生成${NC}"
    fi

    SSL_CERT_PATH="/data/ssl/cert.crt"
    SSL_KEY_PATH="/data/ssl/cert.key"

    # 生成Nginx配置函数
    generate_nginx_config() {
        local system_name=$1
        local install_dir=$2
        local server_name=$3
        local http_port=$4
        local https_port=$5
        
        local conf_file="${NGINX_CONF_DIR}/${system_name}.conf"
        
        echo -e "${GREEN}正在生成Nginx配置: $conf_file${NC}"
        
        # 使用稳定的配置格式
        cat > "$conf_file" <<EOF
# Default server configuration (HTTP on port $http_port)
server {
    listen $http_port;
    listen [::]:$http_port;

    client_max_body_size 100M;
    root $install_dir/public;
    index index.html index.htm index.nginx-debian.html index.php;
    server_name $server_name;

    location / {
        if (!-e \$request_filename) {
            rewrite ^(.*)\$ /index.php?s=/\$1 last;
            break;
        }
    }

    location ~ \.php\$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }

    location /upload {
        client_max_body_size 100M;
    }
    
    access_log /var/log/nginx/${system_name}_access.log;
    error_log /var/log/nginx/${system_name}_error.log;
}

# HTTPS server configuration (SSL on port $https_port)
server {
    listen $https_port ssl;
    listen [::]:$https_port ssl;

    # SSL certificate paths
    ssl_certificate ${SSL_CERT_PATH};
    ssl_certificate_key ${SSL_KEY_PATH};

    # SSL optimization
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:10m;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
    ssl_prefer_server_ciphers on;

    # 以下配置与HTTP版本完全一致
    client_max_body_size 100M;
    root $install_dir/public;
    index index.html index.htm index.nginx-debian.html index.php;
    server_name $server_name;

    location / {
        if (!-e \$request_filename) {
            rewrite ^(.*)\$ /index.php?s=/\$1 last;
            break;
        }
    }

    location ~ \.php\$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }

    location /upload {
        client_max_body_size 100M;
    }
    
    access_log /var/log/nginx/${system_name}_ssl_access.log;
    error_log /var/log/nginx/${system_name}_ssl_error.log;
}
EOF

        # 创建符号链接到sites-enabled
        ln -sf "$conf_file" /etc/nginx/sites-enabled/
        echo -e "${GREEN}✓ Nginx配置生成完成: $system_name${NC}"
    }

    # 为每个系统生成Nginx配置
    if $INSTALL_OA; then
        generate_nginx_config "office" "$OA_INSTALL_DIR" "$SERVER_NAME" "$OA_HTTP_PORT" "$OA_HTTPS_PORT"
    fi

    if $INSTALL_BLOG; then
        generate_nginx_config "blog" "$BLOG_INSTALL_DIR" "$SERVER_NAME" "$BLOG_HTTP_PORT" "$BLOG_HTTPS_PORT"
    fi

    if $INSTALL_DEV; then
        generate_nginx_config "dev" "$DEV_INSTALL_DIR" "$SERVER_NAME" "$DEV_HTTP_PORT" "$DEV_HTTPS_PORT"
    fi

    # 测试Nginx配置并重启
    echo -e "${GREEN}=== 测试Nginx配置 ===${NC}"
    if nginx -t; then
        systemctl reload nginx
        echo -e "${GREEN}✓ Nginx配置测试成功并已重新加载${NC}"
    else
        echo -e "${RED}× Nginx配置测试失败!${NC}"
        echo -e "${YELLOW}请检查Nginx配置文件，然后手动运行: nginx -t${NC}"
        exit 1
    fi
}

# 配置防火墙
configure_firewall() {
    echo -e "${GREEN}=== 配置防火墙 ===${NC}"
    if command -v ufw &>/dev/null && ufw status | grep -q "active"; then
        echo -e "${YELLOW}检测到UFW防火墙已启用，正在配置端口...${NC}"
        if $INSTALL_OA; then
            ufw allow $OA_HTTP_PORT/tcp
            ufw allow $OA_HTTPS_PORT/tcp
        fi
        if $INSTALL_BLOG; then
            ufw allow $BLOG_HTTP_PORT/tcp
            ufw allow $BLOG_HTTPS_PORT/tcp
        fi
        if $INSTALL_DEV; then
            ufw allow $DEV_HTTP_PORT/tcp
            ufw allow $DEV_HTTPS_PORT/tcp
        fi
        echo -e "${GREEN}✓ 防火墙端口配置完成${NC}"
    else
        echo -e "${YELLOW}UFW防火墙未启用，跳过端口配置${NC}"
    fi
}

# 执行配置
echo -e "${BLUE}=== 开始系统配置 ===${NC}"
configure_mysql
install_gougu_systems
set_gougu_permissions
configure_nginx
configure_firewall

###########################################################
#              第五部分：安装完成信息输出                   #
###########################################################

echo -e "${GREEN}=== 勾股系统安装完成 ===${NC}"
echo -e "以下是安装的系统及其访问地址:"

if $INSTALL_OA; then
    echo -e "${YELLOW}=== 勾股OA系统 ===${NC}"
    echo -e "  HTTP: http://${SERVER_NAME}:${OA_HTTP_PORT}"
    echo -e "  HTTPS: https://${SERVER_NAME}:${OA_HTTPS_PORT}"
    echo -e "  数据库: ${OA_MYSQL_DB}"
    echo -e "  安装目录: ${OA_INSTALL_DIR}"
fi

if $INSTALL_BLOG; then
    echo -e "${YELLOW}=== 勾股博客系统 ===${NC}"
    echo -e "  HTTP: http://${SERVER_NAME}:${BLOG_HTTP_PORT}"
    echo -e "  HTTPS: https://${SERVER_NAME}:${BLOG_HTTPS_PORT}"
    echo -e "  数据库: ${BLOG_MYSQL_DB}"
    echo -e "  安装目录: ${BLOG_INSTALL_DIR}"
fi

if $INSTALL_DEV; then
    echo -e "${YELLOW}=== 勾股开发系统 ===${NC}"
    echo -e "  HTTP: http://${SERVER_NAME}:${DEV_HTTP_PORT}"
    echo -e "  HTTPS: https://${SERVER_NAME}:${DEV_HTTPS_PORT}"
    echo -e "  数据库: ${DEV_MYSQL_DB}"
    echo -e "  安装目录: ${DEV_INSTALL_DIR}"
fi

echo -e "\n${GREEN}=== 服务状态 ===${NC}"
echo -e "Nginx: $(systemctl is-active nginx)"
echo -e "MySQL: $(systemctl is-active mysql)"
echo -e "PHP-FPM: $(systemctl is-active php${PHP_VERSION_CURRENT}-fpm)"

echo -e "\n${GREEN}公共配置信息:${NC}"
echo -e "SSL证书信息:"
echo -e "  证书路径: /data/ssl/cert.crt"
echo -e "  私钥路径: /data/ssl/cert.key"
echo -e "  注意: 此为自签名证书，生产环境请使用受信任的CA签发证书${NC}"
echo -e "MySQL信息:"
echo -e "  主机: ${MYSQL_HOST}"
echo -e "  端口: ${MYSQL_PORT}"
echo -e "PHP版本: ${PHP_VERSION_CURRENT}"
echo -e "${YELLOW}请根据需要进行进一步的配置!${NC}"

# 下载升级
wget -qN https://gitee.com/banban1000/docker/raw/master/sh/gouguupdate.sh -O /data/gouguupdate.sh && chmod +x /data/gouguupdate.sh
wget -qN https://gitee.com/banban1000/docker/raw/master/sh/readgouguupdate.sh -O /data/readgouguupdate.sh && chmod +x /data/readgouguupdate.sh

# 显示可能需要的后续操作
echo -e "\n${BLUE}=== 后续操作建议 ===${NC}"
if [ "$PHP_VERSION_CURRENT" != "8.3" ]; then
    echo -e "${YELLOW}注意: 检测到您使用的是PHP $PHP_VERSION_CURRENT，建议升级到PHP 8.3以获得最佳兼容性${NC}"
fi
echo -e "1. 访问上述URL完成系统初始化配置"
echo -e "2. 如需使用域名访问，请配置DNS解析"
echo -e "3. 生产环境建议使用正式的SSL证书替换自签名证书"
echo -e "4. 定期备份数据库和应用程序文件"
echo -e "5. 如果遇到重定向问题，请检查应用程序的路由配置"
